package com.fxu.framework.biz.aop;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.fxu.framework.biz.ano.UseRedis;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import com.fxu.framework.core.holder.RedisHolder;

import java.lang.reflect.Method;

import static com.fxu.framework.biz.aop.LoggerAspect.getArgs;
import static com.fxu.framework.biz.aop.LoggerAspect.getStackTrace;

/**
 * 使用Redis缓存
 * @author fangxu
 * @version 1.0.0
 */
@Slf4j
@Aspect
@Component
public class UseRedisAspect {
    @Pointcut("@annotation(com.fxu.framework.biz.ano.UseRedis)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        UseRedis useRedis = method.getAnnotation(UseRedis.class);
        String args = getArgs(joinPoint.getArgs());
        String redisKey = useRedis.prefix();
        if (StrUtil.isEmpty(redisKey)) redisKey = signature.getDeclaringType() + "." + method.getName();
        return RedisHolder.getIfNullSet(SecureUtil.md5(redisKey + ":" + args), useRedis.second(), () -> {
            try {
                return joinPoint.proceed();
            } catch (Throwable e) {
                log.info("UseRedis error! {}.{}({}), e={}", signature.getDeclaringType(), method.getName(), args,
                        getStackTrace(e));
            }
            return null;
        });
    }

    // 配置异常通知
    @AfterThrowing(pointcut = "pointcut()", throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, Throwable e) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String args = getArgs(joinPoint.getArgs());
        log.info("UseRedis error! {}.{}({}), e={}", signature.getDeclaringType(), method.getName(), args,
                getStackTrace(e));
    }
}
